package com.atguigu.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.Permission;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Component
public class MyUserDetailService implements UserDetailsService {
    //注意哦,要用远程的服务,必须要dubbo配置文件也扫描到这里.
    @Reference
    private AdminService adminService;
    @Reference
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据输入的用户名查找到用户对象
        Admin admin = adminService.getByUsername(username);
        //判断用户是否查询到,如果admin为空说明用户名错误了,直接返回异常
        if(admin==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //admin不为空,就比较密码,这里不需要我们来写代码比较,SpringSecurity来完成密码比较
        Collection<GrantedAuthority> authorities=new ArrayList<>();
        /*    authorities.add(new SimpleGrantedAuthority("role_add"));
        authorities.add(new SimpleGrantedAuthority("admin_delete"));*/
        //动态的获取权限列表  根据用户ID   也就是adminId来获取
        List<String> codeList = permissionService.findCodeListByAdminId(admin.getId());
        for (String code : codeList) {
            authorities.add(new SimpleGrantedAuthority(code));
        }
        //第三个参数是权限列表,如果比对成功,就具有第三个参数里的权限
        User user=new User(username,admin.getPassword(),authorities);
        //只需要返回user即可.SpringSecurity来完成密码比较,如果密码正确,说明登录成功,授予authorities权限
        return user;
    }
}
